//
//  WCANetworkManager.m
//  WeChatAssistant
//
//  Created by Guo Rui on 2017/11/23.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "WCASessionManager.h"


@interface WCASessionManager()
@property (copy, nonatomic) NSString *baseURLString;
@property (strong, nonatomic) NSURLSession *sesstion;
@property (strong, nonatomic) WCAHTTPRequestSerializer *serializtion;
@end

@implementation WCASessionManager

+ (instancetype)manager
{
    static WCASessionManager *mag = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mag = [[WCASessionManager alloc] init];
    });
    return mag;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.sesstion = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        self.serializtion = [WCAHTTPRequestSerializer serializer];
        
        NSUserDefaults *dlts = [NSUserDefaults standardUserDefaults];
        BOOL devEnvironment = [dlts boolForKey:@"devEnvironment"];
        devEnvironment = YES;
        NSInteger appType = 2;
        if (appType == 1) {
            if (devEnvironment) {
                // 是测试环境
                _baseURLString = @"http://stg2.v5time.net/";
            }
            else {
                _baseURLString = @"http://www.timeface.cn/";
            }
        }
        else if (appType == 2) {
            if (devEnvironment) {
                // 是测试环境
                _baseURLString = @"http://stg2.v5time.net/";
            }
            else {
                _baseURLString = @"http://www.timeface.cn/";
            }
        }
        

        
        self.requestHeaderFieldValueDictionary = @{ @"VERSION" : @"1",
                                                    @"TOKEN" : @"Timeface-iOS",
                                                    @"DEVICEID" :[[[UIDevice currentDevice] identifierForVendor] UUIDString]
                                                    }.mutableCopy;
    }
    return self;
}

- (void)setBaseURLString:(NSString *)urlString
{
    _baseURLString = urlString;
}

+ (void)setRequestSerialization:(WCAHTTPRequestSerializer *)serializtion
{
    [WCASessionManager manager].serializtion = serializtion;
}

+ (NSURLSessionDataTask *)GET:(NSString *)url parameters:(id)parameters success:(WCARequestSuccessBlock)success failure:(WCARequestFailureBlock)failure
{
    WCASessionManager *mag = [WCASessionManager manager];
    NSError *error = nil;
    
    if (mag.requestHeaderFieldValueDictionary) {
        [mag.requestHeaderFieldValueDictionary enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [mag.serializtion setValue:obj forHTTPHeaderField:key];
        }];
    }
    
    NSURLRequest *request = [mag.serializtion requestWithMethod:@"GET" URLString:[mag.baseURLString stringByAppendingPathComponent:url] parameters:parameters error:&error];
    NSLog(@"url : %@, param : %@", request.URL, parameters);
    __block NSURLSessionDataTask *dataTask = nil;
    dataTask = [mag.sesstion dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error && failure) {
            failure(dataTask, error);
        }
        else if (success) {
            NSError *error = nil;
            id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
            if (error) {
                failure(dataTask, error);
            }
            else {
                success(dataTask, obj);
            }
        }
    }];
    
    [dataTask resume];
    return dataTask;
}

+ (NSURLSessionDataTask *)POST:(NSString *)url parameters:(id)parameters success:(WCARequestSuccessBlock)success failure:(WCARequestFailureBlock)failure
{
    WCASessionManager *mag = [WCASessionManager manager];
    NSError *error = nil;
    
    if (mag.requestHeaderFieldValueDictionary) {
        [mag.requestHeaderFieldValueDictionary enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [mag.serializtion setValue:obj forHTTPHeaderField:key];
        }];
    }
    
    NSURLRequest *request = [mag.serializtion requestWithMethod:@"POST" URLString:[mag.baseURLString stringByAppendingPathComponent:url] parameters:parameters error:&error];
    
    NSLog(@"url : %@, param : %@", request.URL, parameters);
    __block NSURLSessionDataTask *dataTask = nil;
    dataTask = [mag.sesstion dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error && failure) {
            NSLog(@"network error - %@", error);
            failure(dataTask, error);
        }
        else if (success) {
            NSError *er = nil;
            id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&er];
            if (er) {
                NSLog(@"paise error - %@", er);
                failure(dataTask, er);
            }
            else {
                success(dataTask, obj);
            }
        }
    }];
    
    [dataTask resume];
    return dataTask;
}

@end
